package com.gouldzd.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.gouldzd.pojo.Permission;
import com.gouldzd.pojo.Role;
import com.gouldzd.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/*
 * @Author zhangdan
 * @Description //TODO Security权限控制服务
 * @Date 10:54 2020/5/7
 * @Param
 * @return
 **/
@Component
public class SpringSecurityUserService implements UserDetailsService {

    //使用dubbo通过网络远程调用服务提供方获取数据库中的用户信息
    @Reference
    private UserService userService;

    //根据用户名查询数据库
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户
        User user = userService.findByUsername(username);
        if(user == null){
            //用户名不存在
            return null;
        }

        //创建list集合,泛型:SpringSecurity框架的GrantedAuthority,用于存放权限
        List<GrantedAuthority> list = new ArrayList<>();

        //动态为当前用户授权
        Set<Role> roles = user.getRoles();//获取用户的角色
        //遍历角色集合,为用户授予角色
        for (Role role : roles) {
            list.add(new SimpleGrantedAuthority(role.getKeyword()));

            Set<Permission> permissions = role.getPermissions();//获取用户的操作权限
            //遍历权限集合,为用户授权
            for (Permission permission : permissions) {
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }

        //SpringSecurity框架的User对象
        org.springframework.security.core.userdetails.User securityUser = new org.springframework.security.core.userdetails.User(username, user.getPassword(), list);

        return securityUser;
    }
}
